﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Security.Permissions;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.Globalization;
using System.Threading;

namespace wfjn
{
    [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
    public partial class Form1 : Form
    {
        public static FileSystemWatcher watcher = new FileSystemWatcher();
        public string filepath = "";
        public Form1()
        {
            filepath = ConfigurationManager.AppSettings["p"].ToString();
            InitializeComponent();
            Form.CheckForIllegalCrossThreadCalls = false;
        }
        private void OnChanged(object source, FileSystemEventArgs e)
        {
            txtmsg.Text += "文件: " + e.FullPath + " " + e.ChangeType +" 时间："+DateTime.Now.ToString()+ "\r\n";
            addfile(e.FullPath);
        }
        private void OnDel(object source, FileSystemEventArgs e)
        {
            txtmsg.Text += "文件: " + e.FullPath + " " + e.ChangeType + " 时间：" + DateTime.Now.ToString() + "\r\n";
            //onaddfile(e.FullPath);
        }
        private void OnRenamed(object source, RenamedEventArgs e)
        {            
            txtmsg.Text += string.Format("File: {0} renamed to {1}", e.OldFullPath, e.FullPath) + "\r\n";
            addfile(e.FullPath);
        }
        private void AutoRun_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked)//开机自动启动
            {
                try
                {
                    RegistryKey runKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
                    runKey.SetValue("wfjn.exe", System.Windows.Forms.Application.ExecutablePath);
                    runKey.Close();
                }
                catch (IOException)
                {
                    return;
                }
            }
            else  //不开机自动启动注册表信息删除
            {
                RegistryKey software = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
                string[] aimnames = software.GetValueNames();
                foreach (string aimKey in aimnames)
                {
                    if (aimKey.Equals("wfjn.exe"))
                    {
                        software.DeleteValue("wfjn.exe");
                        software.Close();
                        break;
                    }
                }
            }
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            //AutoRun_CheckedChanged(null, null);
            //scanfile();
            

            watcher.Path = filepath;
            /* Watch for changes in LastAccess and LastWrite times, and
               the renaming of files or directories. */
            watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
               | NotifyFilters.FileName | NotifyFilters.DirectoryName;
            // Only watch text files.
            watcher.Filter = "*.jpeg";

            //watcher.Changed += new FileSystemEventHandler(OnChanged);
            watcher.Created += new FileSystemEventHandler(OnChanged);
            watcher.Deleted += new FileSystemEventHandler(OnDel);
            watcher.Renamed += new RenamedEventHandler(OnRenamed);
            watcher.EnableRaisingEvents = true;
        }
        private void addfile(string file)
        {
            try
            {
                FileInfo fl;
                string name;
                string did, uptime;
                DateTime dt;
                uppicsinfom m = new uppicsinfom();
                uppicsinfo dm = new uppicsinfo();
                fl = new FileInfo(file);
                name = fl.Name;
                if (name.Split('_').Length == 3)
                {
                    did = name.Split('_')[0];
                    uptime = name.Split('_')[1];
                    if (uptime.Length > 14)
                        uptime = uptime.Substring(0, 14);
                    dt = DateTime.ParseExact(uptime, "yyyyMMddHHmmss", CultureInfo.InvariantCulture);
                    m.bpid = did;
                    m.ptime = dt;
                    m.ptstr = name;
                    m.uptime = DateTime.Now;
                    dm.Add(m);
                }
            }
            catch (Exception ex)
            { }
        }
        private void delfile(string file)
        {
            FileInfo fl;
            string name;
            string did, uptime;
            DateTime dt;
            uppicsinfom m = new uppicsinfom();
            uppicsinfo dm = new uppicsinfo();
            fl = new FileInfo(file);
            name = fl.Name;
            if (name.Split('_').Length == 3)
            {
                did = name.Split('_')[0];
                uptime = name.Split('_')[1];
                if (uptime.Length > 14)
                    uptime = uptime.Substring(0, 14);
                dt = DateTime.ParseExact(uptime, "yyyyMMddHHmmss", CultureInfo.InvariantCulture);
                m.bpid = did;
                m.ptime = dt;
                m.ptstr = name;                
                dm.Delete(m.ptstr);
            }
        }
        private void scanfile()
        {
            try
            {
                string[] f = Directory.GetFiles(filepath, "*.*");
                FileInfo fl;
                string name;
                string did, uptime;
                DateTime dt;
                uppicsinfom m = new uppicsinfom();
                uppicsinfo dm = new uppicsinfo();
                foreach (string fi in f)
                {
                    fl = new FileInfo(fi);
                    name = fl.Name;
                    if (name.Split('_').Length == 3)
                    {
                        did = name.Split('_')[0];
                        uptime = name.Split('_')[1];
                        if (uptime.Length > 14)
                            uptime = uptime.Substring(0, 14);
                        dt = DateTime.ParseExact(uptime, "yyyyMMddHHmmss", CultureInfo.InvariantCulture);
                        m.bpid = did;
                        m.ptime = dt;
                        m.ptstr = name;
                        m.uptime = DateTime.Now;
                        if (dm.Add(m) != 0)
                            txtmsg.Text += "增加数据文件: " + m.ptstr + " 系统扫描" + " 时间：" + DateTime.Now.ToString() + "\r\n";
                        //else
                        //     txtmsg.Text += "数据文件: " + m.ptstr + "在数据库中存在 系统扫描" + " 时间：" + DateTime.Now.ToString() + "\r\n";
                        txtmsg.Refresh();
                    }
                }
                txtmsg.Text += "系统扫描完成！" + " 时间：" + DateTime.Now.ToString() + "\r\n";
                txtmsg.Refresh();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private void button1_Click(object sender, EventArgs e)
        {
            ThreadStart start = null;
            if (start == null)
            {
                start = duibifile;
            }
            Thread t = new Thread(start);
            t.IsBackground = true;
            t.Start();
            
        }
        private void duibifile()
        {
            uppicsinfom m = new uppicsinfom();
            uppicsinfo dm = new uppicsinfo();
            DataSet ds = dm.GetList("");
            string ptstr = "";

            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                ptstr = ds.Tables[0].Rows[i]["ptstr"].ToString();
                string[] f = Directory.GetFiles(filepath, ptstr);
                if (f.Length < 1)
                {
                    dm.Delete(ptstr);
                    txtmsg.Text += "删除数据库记录文件： " + ptstr + " 时间：" + DateTime.Now.ToString() + "\r\n";
                    txtmsg.Refresh();
                }
                //else {
                //    txtmsg.Text += "数据库记录文件： " + ptstr + "本地存在 时间：" + DateTime.Now.ToString() + "\r\n";
                //    txtmsg.Refresh();
                //}
            }
            txtmsg.Text += "数据库记录同步完成！" + " 时间：" + DateTime.Now.ToString() + "\r\n";
            txtmsg.Refresh();
        }
            
        private void txtmsg_TextChanged(object sender, EventArgs e)
        {
            if (txtmsg.Lines.Length > 100) txtmsg.Text = "";
            this.txtmsg.SelectionStart = this.txtmsg.Text.Length;
            this.txtmsg.SelectionLength = 0;
            this.txtmsg.ScrollToCaret();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.txtmsg.Text = "";
        }

        private void button3_Click(object sender, EventArgs e)
        {
            ThreadStart start = null;
            if (start == null)
            {
                start = scanfile;
            }
            Thread t = new Thread(start);
            t.IsBackground = true;
            t.Start();

        }
    }
}
